@tool
class_name FlipPanel extends Control

var type
## 获取场景节点
var father
# 翻转卡牌效果
@onready var behind: TextureRect = $Behind
@onready var front: TextureRect = $Front
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var texture_button: TextureButton = %TextureButton
@onready var label: Label = %Label

signal flip
signal burning

@export_range(0.0,180.0) var y_rot = 0.0:
	set(value):
		y_rot = value
		if front:
			front.material.set("shader_parameter/y_rot",value)
		if behind:
			behind.material.set("shader_parameter/y_rot",(180.0-value)*-1)

func _ready() -> void:
	texture_button.mouse_entered.connect(_on_texture_button_mouse_entered)
	texture_button.mouse_exited.connect(_on_texture_button_mouse_exited)
	texture_button.pressed.connect(_on_texture_button_pressed)
	
func flip_anim():
	animation_player.play("flip_anim", -1, 2)

func flip_back_anim():
	animation_player.play("flip_anim", -1, -2, true)

func burning_anim():
	animation_player.play("burning_anim", -1, 2)

# 鼠标进入时按钮放大
func playAnim(target):
	target.pivot_offset = target.size/2
	var tween = create_tween()
	tween.tween_property(target,"scale",Vector2(1.1,1.1),0.1)
	
# 鼠标离开时按钮还原
func playAnim1(target):
	target.pivot_offset = target.size/2
	var tween = create_tween()
	tween.tween_property(target,"scale",Vector2(1.0,1.0),0.1)
	
# 松开按钮时按钮收缩回原尺寸
func playAnim2(target):
	var tween = create_tween()
	tween.tween_property(target,"scale",Vector2(0.9,0.9),0.1)
	await tween.finished

func _on_texture_button_mouse_entered() -> void:
	playAnim(behind)

func _on_texture_button_mouse_exited() -> void:
	playAnim1(behind)

func _on_texture_button_pressed() -> void:
	await playAnim2(behind)
	if father.attempts_left <= 0:
		return
	emit_signal("flip", self)
	flip_anim()
	await animation_player.animation_finished
	

func _on_animation_player_animation_finished(anim_name: StringName) -> void:
	if anim_name == "burning_anim":
		emit_signal("burning")
